package main

import (
	"fmt"
	"sync"
)

func createWorker(id int, c chan int, wg *sync.WaitGroup) {
	defer wg.Done()

	for {
		data, ok := <-c
		if !ok {
			// channel已关闭
			break
		}
		fmt.Printf("Worker %d received %c\n", id, data)
	}
}

func chanDemo() {

	var wg sync.WaitGroup
	var channels [10]chan int

	// 增加计数器，表示有10个goroutine要等待
	wg.Add(10)

	for i := 0; i < 10; i++ {
		channels[i] = make(chan int)
		// 分发10个worker
		go createWorker(i, channels[i], &wg)
	}

	// 向通道发送数据
	for i := 0; i < 10; i++ {
		channels[i] <- 'a' + i
	}

	// 向通道发送数据
	for i := 0; i < 10; i++ {
		channels[i] <- 'A' + i
	}

	// 关闭所有通道，通知goroutine停止接收
	for i := 0; i < 10; i++ {
		close(channels[i])
	}

	// 等待所有goroutine完成
	wg.Wait()
}

func main() {
	chanDemo()

	fmt.Println("All goroutines completed.")
}
